﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Lon.Dev;
using Lon.IO;
using Lon.Util;

namespace Lon
{
    public partial class FormMain : Form, IMessageShower, IRawDataShower
    {
        private CommDevice commDev;
        public FormMain()
        {
            InitializeComponent();
            InitDebugInfo();
            InitRawDataInfo();
            String path = Path.Combine(Environment.CurrentDirectory, "SensorNetUpdate.ini");

            IniDoc cfg = new IniDoc(path);
            cfg.Load();
            String ip = cfg.GetString("全局配置", "IP");
            if (String.IsNullOrEmpty(ip))
            {
                ip = "192.168.1.138";
            }
            commDev = new CommDevice(ip);
            commDev.RawDataShower = this;
            commDev.MessageShower = this;
            commDev.Start();

        }

        private void InitRawDataInfo()
        {
            ColumnHeader ch = new ColumnHeader();

            ch.Text = "方向";   //设置列标题 

            ch.Width = 120;    //设置列宽度 

            ch.TextAlign = HorizontalAlignment.Left;   //设置列的对齐方式 

            this.lvRawData.Columns.Add(ch);    //将列头添加到ListView控件。  

            ColumnHeader chInfo = new ColumnHeader();

            chInfo.Text = "数据";   //设置列标题 

            chInfo.Width = 1000;

            chInfo.TextAlign = HorizontalAlignment.Left;   //设置列的对齐方式 

            this.lvRawData.Columns.Add(chInfo);    //将列头添加到ListView控件。 
        }

        private void InitDebugInfo()
        {
            ColumnHeader ch = new ColumnHeader();

            ch.Text = "类型";   //设置列标题 

            ch.Width = 120;    //设置列宽度 

            ch.TextAlign = HorizontalAlignment.Left;   //设置列的对齐方式 

            this.lvDebugInfo.Columns.Add(ch);    //将列头添加到ListView控件。  

            ColumnHeader chInfo = new ColumnHeader();

            chInfo.Text = "信息";   //设置列标题 

            chInfo.Width = 1000;

            chInfo.TextAlign = HorizontalAlignment.Left;   //设置列的对齐方式 

            this.lvDebugInfo.Columns.Add(chInfo);    //将列头添加到ListView控件。  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            commDev.SetDebugMode((byte)int.Parse(this.txtPortNo.Text), true);

        }

        public void ShowMessage(String type, String message)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = type;
                    lvi.SubItems.Add(message);
                    this.lvDebugInfo.Items.Add(lvi);
                }));
            }
            else
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = type;
                lvi.SubItems.Add(message);
                this.lvDebugInfo.Items.Add(lvi);
            }

        }
        Queue<KeyValuePair<String, byte[]>> rawDataQueue = new Queue<KeyValuePair<string, byte[]>>();
        public void ShowRawData(String dir, Byte[] data)
        {
            if (filterPortNo != -1)
            {
                if (data[1] != filterPortNo)
                {
                    return;
                }
            }
            if (filterDevNo != -1)
            {
                if (filterDevNo != data[13])
                {
                    return;
                }
            }
            lock (this.rawDataQueue)
            {
                this.rawDataQueue.Enqueue(new KeyValuePair<string, byte[]>(dir, data));
            }






        }


        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            commDev.SetDebugMode((byte)int.Parse(this.txtPortNo.Text), false);
        }

        private void btnQueryStatu_Click(object sender, EventArgs e)
        {
            commDev.QueryDebugMode((byte)int.Parse(this.txtPortNo.Text));
        }



        private void button3_Click(object sender, EventArgs e)
        {
            commDev.UIQueryVer((byte)int.Parse(this.txtPortNo.Text), (byte)int.Parse(this.txtDstAddr.Text));


        }

        private void button4_Click(object sender, EventArgs e)
        {
            String path = this.txtFilePath.Text;
            if (File.Exists(path) == false)
            {
                MessageBox.Show("文件不存在", "错误");
                return;
            }
            commDev.PortNo = int.Parse(this.txtPortNo.Text);
            commDev.DevId = int.Parse(this.txtDstAddr.Text);
            commDev.Update(path);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            commDev.QueryVer();
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Hex|*.hex|A43|*.a43";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                this.txtFilePath.Text = ofd.FileName;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            String path = this.txtFilePath.Text;
            if (File.Exists(path) == false)
            {
                MessageBox.Show("文件不存在", "错误");
                return;
            }
            commDev.PortNo = int.Parse(this.txtPortNo.Text);
            commDev.DevId = int.Parse(this.txtDstAddr.Text);
            commDev.Test(path);
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            for (int i = 0; i < 1000; i++)
            {
                byte[] data = new byte[8];
                Array.Copy(BitConverter.GetBytes(i), data, 4);
                commDev.WriteCanFrame(0x00, 0x10, data);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.lvRawData.Items.Clear();
        }

        private int filterPortNo = -1;
        private int filterDevNo = -1;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            filterPortNo = StringHelper.ToInt(((TextBox)sender).Text, -1);

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            filterDevNo = StringHelper.ToInt(((TextBox)sender).Text, -1);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            KeyValuePair<String, byte[]>[] keyValueArr = null;
            lock (this.rawDataQueue)
            {
                keyValueArr = this.rawDataQueue.ToArray();
                this.rawDataQueue.Clear();
            }
            if (keyValueArr == null || keyValueArr.Length == 0)
            {
                return;
            }
            for (int i = 0; i < keyValueArr.Length; i++)
            {
                var pair = keyValueArr[i];
                var dir = pair.Key;
                var data = pair.Value;
                ListViewItem lvi = new ListViewItem();
                if (data.Length > 10)
                {
                    lvi.Text = String.Format("{0}({1:dd:mm:ss.fff})", dir,
                        DateTimeHelper.UnixTime2DateTime(BitConverter.ToUInt32(data, 2))
                            .AddMilliseconds(BitConverter.ToInt32(data, 6)/1000.0));
                    lvi.SubItems.Add(StringHelper.ByteArr2HexString(data));
                }
                else
                {
                    lvi.Text = dir;
                    lvi.SubItems.Add(StringHelper.ByteArr2HexString(data));
                }
                this.lvRawData.Items.Add(lvi);
                if (this.lvRawData.Items.Count > 10000)
                {
                    this.lvRawData.Items.RemoveAt(0);
                }
            }
          
            this.lvRawData.Items[this.lvRawData.Items.Count - 1].EnsureVisible();
        }



    }
}
